package edu.seu.mart.utils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import edu.seu.mart.model.EventMsg;
import edu.seu.mart.model.NewsMsg;
import edu.seu.mart.model.TextMsg;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息处理工具类
 */
public class MsgKit {

    /**
     * 解析微信端传过来的XML
     */
    public static Map<String, String> parseXml(InputStream inputStream) {
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(inputStream);
            Element root = document.getRootElement();
            List<Element> elementList = root.elements();
            for (Element e : elementList) {
                map.put(e.getName(), e.getTextTrim());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 文本消息转为XML
     */
    public static String textMsgToXml(TextMsg textMsg) {
        XStream xStream = getXStream();
        xStream.alias("xml", TextMsg.class);
        String xml = xStream.toXML(textMsg);
        return replace(xml);
    }

    /**
     * 图文消息转为XML
     */
    public static String newsMsgToXml(NewsMsg newsMsg) {
        XStream xStream = getXStream();
        xStream.alias("xml", NewsMsg.class);
        String xml = xStream.toXML(newsMsg);
        return replace(xml);
    }

    /**
     * 图文消息转为XML
     */
    public static String eventMsgToXml(EventMsg eventMsg) {
        XStream xStream = getXStream();
        xStream.alias("xml", EventMsg.class);
        String xml = xStream.toXML(eventMsg);
        return replace(xml);
    }

    /**
     * 增加CDATA
     */
    public static String addCData(String text) {
        if (text != null) {
            return "<![CDATA[" + text + "]]>";
        }
        return null;
    }

    /**
     * 替换字符，使CDATA显示正确
     */
    public static String replace(String xml) {
        return xml.replaceAll("&lt;", "<").replaceAll("&gt;", ">")
                .replaceAll("&quot;", "\"").replaceAll("&amp;", "&");
    }

    /**
     * XStream
     */
    public static XStream getXStream() {
        XStream xStream = new XStream(new DomDriver());
        xStream.autodetectAnnotations(true);
        return xStream;
    }
}
